package com.mind.ridge.service.front.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mind.ridge.mapper.front.UserMapper;
import com.mind.ridge.pojo.front.User;
import com.mind.ridge.service.front.UserService;
import com.mind.ridge.utils.R;
import com.mind.ridge.utils.SMSUtils;
import com.mind.ridge.utils.ValidateCodeUtils;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author Mind
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public R<User> sendMsg(User user, HttpServletRequest request) {
        if (user == null) {
            return R.error("ERROR！");
        }
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.info(code.toString());
        HttpSession session = request.getSession();
        session.setAttribute("smsCode", code);
        return R.success(user);
    }

    @Override
    public R<String> login(Map<String, String> map, HttpServletRequest request) {
        String phone = map.get("phone");
        String code = map.get("code");
        if (!Strings.isNotEmpty(phone) || !Strings.isNotEmpty(code)) {
            return R.error("ERROR");
        }
        String smsCode = String.valueOf(request.getSession().getAttribute("smsCode"));
        if (code.equals(smsCode)) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = this.getOne(wrapper);
            log.info("用户信息：{}", user);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                this.save(user);
            }
            Long userId = user.getId();
            request.getSession().setAttribute("userId", userId);
            return R.success("Login Successfully");
        }
        return R.error("ERROR");
    }
}
